<template>
  <div>
    <CustomTable
      ref="customTableRef"
      url="/file/search/import-list"
      :searchInfo="searchInfo"
      methods="post"
      :loading="true"
      :columns="columns"
    >
      <template #searchPre>
        <div class="dib upload-0023"></div>
      </template>
      <template #searchAfter>
        <div class="dib upload-0023 ml10">
          <el-button
            type="info"
            plain
            icon="Upload"
            @click="handleImport"
            size="small"
          >
            导入
          </el-button>
          <el-button
            size="small"
            @click="handleReadFileInService"
            type="warning"
          >
            一键读取文件
          </el-button>
        </div>
      </template>
      <template #status="{ data }">
        <el-tag :type="data.status === 1 ? '' : 'danger'">
          <span>
            {{
              data.status === 0 ? '未导入' : data.status === 1 ? '成功' : '失败'
            }}
          </span>
        </el-tag>
      </template>
      <template #option="{ data }">
        <el-button type="primary" size="small" @click="handleAsync(data)">
          同步工商信息
        </el-button>
      </template>
    </CustomTable>

    <el-dialog
      :title="upload.title"
      v-model="upload.open"
      width="400px"
      append-to-body
    >
      <el-input v-model="batchName" placeholder="请输入批次名"></el-input>
      <el-upload
        ref="uploadRef"
        style="margin-top: 20px"
        multiple
        :action="upload.url"
        :on-change="handleChange"
        accept=".xls,.xlsx"
        :auto-upload="false"
        list-type="text"
        name="files"
      >
        <el-button type="primary">选择文件</el-button>
      </el-upload>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitUpload">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="UploadFile">
import { getBatchUpdate } from '@/api/uploadFile.js'
import { getToken } from '@/utils/auth'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'
import { provide, reactive, ref } from 'vue'

import axios from 'axios' // 确保安装了 axios

const { proxy } = getCurrentInstance()

const customTableRef = ref()
const searchInfo = ref([
  { key: 'fileName', label: '文件名' },
  {
    key: 'queryDate',
    label: '查询周期',
    type: 'dateRange',
    keys: ['createTimeStart', 'createTimeEnd'],
  },
])

const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: 'Bearer ' + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/file/import/upload',
  batchName: '',
})

const columns = ref([
  {
    prop: 'batchName',
    minWidth: 260,
    label: '批次名',
    fixed: 'left',
  },
  {
    prop: 'fileName',
    minWidth: 260,
    label: '文件名',
  },
  {
    prop: 'createTime',
    minWidth: 180,
    label: '创建时间',
  },
  //{
  //   prop: "importNum",
  //   minWidth: 80,
  //   label: "导入记录数",
  // },
  {
    prop: 'excelNum',
    label: '源文件记录数',
  },
  {
    prop: 'status',
    width: 100,
    label: '状态',
  },
  //   {
  //     prop: 'option',
  //     width: 150,
  //     label: '操作'
  //   }
])

const updateSuccess = (e) => {
  console.log(e)
}
const handleView = (data) => {
  state.visible = true
  state.id = data.id
  state.data = data
}
const state = reactive({
  visible: false,
  id: null,
})

// 同步工商信息
const handleAsync = (data) => {
  getBatchUpdate({
    batchName: data.batchName,
  }).then((res) => {
    if (res.code === 200) {
      ElMessage({
        message: '同步工商信息成功',
        type: 'success',
      })
    }
  })
}

function handleReadFileInService() {
  request.post('/file/import/company').then((res) => {
    if (res.code === 200) {
      ElMessage.success('读取服务器文件成功！')
    } else {
      ElMessage.error(res.msg)
    }
  })
}

const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true
}
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false
  upload.isUploading = false
  proxy.$refs['uploadRef'].handleRemove(file)
  customTableRef.value.fetchData()
}

/** 导入按钮操作 */
function handleImport() {
  upload.title = '导入'
  upload.open = true
}
/** 提交上传文件 */

const uploadRef = ref(null)

function submitFileForm() {
  proxy.$refs['uploadRef'].submitUpload()
}

const batchName = ref('')
const fileListForUpload = ref([])

const handleChange = (file, fileList) => {
  fileListForUpload.value = [...fileList]
}

const submitUpload = async () => {
  if (fileListForUpload.value.length === 0) {
    ElMessage.warning('请选择文件')
    return
  }

  const formData = new FormData()
  fileListForUpload.value.forEach((file) => {
    formData.append('files', file.raw) // 'files' 是后端接收的字段名
  })
  formData.append('batchName', batchName.value)

  try {
    const response = await axios.post(upload.url, formData, {
      headers: upload.headers,
    })
    // 处理上传成功
    upload.open = false
    ElMessage.success('导入成功！')
    customTableRef.value.fetchData()
  } catch (error) {
    // 处理上传失败
    console.error('上传失败:', error)
  }
}

provide('state', state)
</script>
<style scoped>
::v-deep(.upload-file-uploader) {
  margin-bottom: 0;
  margin-right: 6px;
}
</style>
